from rest_framework.authentication import BaseAuthentication
from rest_framework.permissions import BasePermission
from rest_framework.exceptions import AuthenticationFailed
from rest_framework.response import Response

from app01 import models


class MyAuthentication(BaseAuthentication):
    def authenticate(self, request):
        token = request.GET.get('token')
        if token:
            user_token = models.UserToken.objects.filter(token=token).first()
            if user_token:
                return user_token.user, token
            else:
                raise AuthenticationFailed('认证失败')
        else:
            raise AuthenticationFailed('请携带token')


class UserPermission(BasePermission):
    def has_permission(self, request, view):
        print('view:', view)
        print('view:', view.authentication_classes)
        # 不是超级用户不能访问
        # 由于认证过了， 所以request里面有user对象了
        user = request.user
        print(user.get_user_type_display())
        if user.user_type == 1:
            return True
        else:
            return False


# 自定义异常处理的方法 作用，统一异常处理 2. 返回错误日志
from rest_framework import status
from rest_framework.response import Response


def my_exception_handler(exc, context):
    from rest_framework.views import exception_handler
    response = exception_handler(exc, context=context)
    # response 两种值None和response对象
    print(type(exc))
    if not response:
        print(exc)  # 异常对象
        print(context)
        # 更细的捕获异常
        if isinstance(exc, ZeroDivisionError):
            return Response(data={'status': 777, 'msg': '除以0的错误' + str(exc)}, status=status.HTTP_400_BAD_REQUEST)
        # {'view': <app01.views.TestView5 object at 0x00000227DAD12550>, 'args': (), 'kwargs': {}, 'request': <rest_framework.request.Request: GET '/test4/'>}
        return Response(data={'status': 999, 'msg': str(exc)}, status=status.HTTP_400_BAD_REQUEST)
    else:
        # return response  # 直接返回response对象 不符合我们的规范
        print(response)
        return Response(data={'status': 800, 'msg': response.data.get('detail')}, status=status.HTTP_400_BAD_REQUEST)


# 自己封装response对象
# 返回值为 return APIResponse(100, '成功', data)
from rest_framework.response import Response
class APIResponse(Response):
    def __init__(self, code=100, msg='成功', data=None, status=None, headers=None, **kwargs):
        dic = {'code': code, 'msg': msg}
        if data:
            dic = {'code': code, 'msg': msg, 'data': data}
        dic.update(kwargs)
        super().__init__(data=dic, status=status, headers=headers)